#!/usr/bin/python
# -*- coding:utf-8 -*-   
#encoding=utf-8
#author=daimin
'''
备份游戏日志
'''
import sys
import os
import conf
import nethandler
import datetime
import json

DAILY  = 0
HOUR   = 1
WEEKLY = 2
MONTH  = 3
ALL    = 100

GM_CFG = conf.MODELS['GM']

################################# 日志获取的URL的配置 #########################################
log_urls = {
            "ddd" :{
                      HOUR : {
                              'URLS': [
                                    'http://42.121.16.236:3888/getRegistrationInfo?type=1',\
                                    'http://42.121.16.236:3888/getLoginInfo?type=1', 
                                    'http://42.121.16.236:3888/getRechargeInfo?type=1'
                                      ],
                              'RUN' : 'python %s/main.py -m gm -o 0' % os.path.dirname(__file__),
                              },
                      DAILY : {
                               'URLS' : [
                                    'http://42.121.16.236:3888/getRegistrationInfo?type=1',\
                                    'http://42.121.16.236:3888/getLoginInfo?type=1', 
                                    'http://42.121.16.236:3888/getRechargeInfo?type=1'
                                       ],
                                
                               },
                      ALL   : {
                               'URLS' : [
                                    'http://42.121.16.236:3888/getRegistrationInfo?type=0',\
                                    'http://42.121.16.236:3888/getLoginInfo?type=0', 
                                    'http://42.121.16.236:3888/getRechargeInfo?type=0'
                                        ]
                               }
                },
           }


################################### 具体日志操作类 ####################################################
class GameLog():
    
    def __init__(self, **kwargs):
        pass
    
    def parse(self):
        pass

class DDDLog(GameLog):
    """DDD游戏日志处理
    """
    Name = "ddd"
    
    def __init__(self, **kwargs):
        self.__interval = kwargs['interval'] if 'interval' in kwargs else None
        self.__gcfg     = kwargs['cfg'] if 'cfg' in kwargs else None
        self.__timefmt  = kwargs['timefmt'] if 'timefmt' in kwargs else None
    
    def parse(self):
        intercfg = self.__gcfg.get(self.__interval, None)
        if intercfg is None: return
        logurls = intercfg.get('URLS', None)
        if logurls is None: return
        gamecfg =  GM_CFG['games'].get(DDDLog.Name, None)
        if gamecfg is None: return
        logdir = gamecfg['dir'] if  'dir' in gamecfg else GM_CFG['dir']
        with open(os.path.join(logdir, 'act.game.ddd.%s.log') % self.__timefmt, 'w') as logf:
            for u in logurls:
                logdata = nethandler.get(u)
                jsonObj = None
                try:
                    jsonObj = json.loads(logdata)
                except:
                    pass
                if jsonObj is None:continue
                for jo in jsonObj:
                    logf.write(jo['data'].replace('|','\n') if 'data' in jo else '')
                logf.write('\n')
        
        runcmd = intercfg.get('RUN', None)
        if runcmd is None: return
        os.system(runcmd)
        


def main():
    if len(sys.argv) < 2:
        print u'请指定运行时间间隔：\n\t%d：每天运行一次；%d：每小时运行一次，%d：每周运行一次，%d：每月运行一次，%d：运行所有'\
               %(DAILY, HOUR, WEEKLY, MONTH, ALL )
        exit()
    interval = -1
    try:
        interval = int(sys.argv[1])
    except:
        pass
    
    if interval == -1 or interval not in (DAILY, HOUR, WEEKLY, MONTH, ALL):
        print u'无效的时间间隔!!!请指定运行时间间隔：\n\t%d：每天运行一次；%d：每小时运行一次，%d：每周运行一次，%d：每月运行一次，%d：运行所有'\
         % (DAILY, HOUR, WEEKLY, MONTH, ALL)       
        exit()
    
    nowf   = datetime.datetime.now()
    nowfmt = nowf.strftime("%y%m%d")
    for (gname, gcfg) in log_urls.items():
        mod = getattr(sys.modules[GameLog.__module__], '%sLog' %(gname.upper()))
        mod(interval = interval, cfg = gcfg, timefmt = nowfmt).parse()

if __name__ == '__main__':
    reload(sys)
    sys.setdefaultencoding('utf-8')
    main()
    
    
